package growth

import (
	"clientDemo/service/modulemgr"
	"sync"
)

var Name = "goroutine-mod"

type IGoroutinePoolModule interface {
	modulemgr.IModule
}

// GoroutinePool 结构体定义
type GoroutinePool struct {
	taskChan chan func() // 任务通道
	wg       sync.WaitGroup
}

// NewGoroutinePool 创建协程池
func NewGoroutinePool(size int) *GoroutinePool {
	pool := &GoroutinePool{
		taskChan: make(chan func(), size),
	}
	pool.wg.Add(size)
	for i := 0; i < size; i++ {
		go pool.worker()
	}
	return pool
}

// worker 工作协程逻辑
func (p *GoroutinePool) worker() {
	defer p.wg.Done()
	for task := range p.taskChan {
		task()
	}
}

// Submit 提交任务
func (p *GoroutinePool) Submit(task func()) {
	p.taskChan <- task
}

// Shutdown 关闭协程池
func (p *GoroutinePool) Shutdown() {
	close(p.taskChan)
	p.wg.Wait()
}
